//
//  LDAddressPickerView.m
//  zhilian
//
//  Created by 李丹 on 2019/7/23.
//  Copyright © 2019 LZT. All rights reserved.
//

#pragma mark - 选择器数据源model

#import "LDAddressPickerView.h"
@implementation LDPickerItem
- (void) loadData:(NSInteger)count config:(void(^)(LDPickerItem *item, NSInteger index)) config {
    if (count <= 0) {
        NSLog(@"至少需要一个数据源！");
        return;
    }
    NSMutableArray *temps = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i < count; i++) {
        LDPickerItem *city = [[LDPickerItem alloc] init];
        if (config) {
            config(city, i);
        }
        [temps addObject:city];
    }
    
    self.datas = [NSArray arrayWithArray:temps];
}
#pragma mark - /** 加载数据源 */
+ (NSMutableArray *)loadData {
    
    NSMutableArray *dataSource = [NSMutableArray array];
//    NSString *path = [[NSBundle mainBundle]pathForResource:@"Address" ofType:@"plist"];
    
//    NSMutableArray *dic = [[NSMutableArray alloc]initWithContentsOfFile:path];
//    for (NSDictionary *tmp in provinces) {
//        // 创建第一级数据
//        LDPickerItem *item1 = [[LDPickerItem alloc]init];
//        item1.name = [[tmp allKeys] firstObject];
//        NSDictionary *arr = [tmp objectForKey:item1.name];
//        NSArray *keys = arr.allKeys;
//        // 配置第二级数据
//        [item1 loadData:keys.count config:^(LDPickerItem *item, NSInteger index) {
//
//            item.name = keys[index];
//            NSArray *area = [arr objectForKey:item.name];
//            // 配置第三极数据
//            [item loadData:area.count config:^(LDPickerItem *item, NSInteger index) {
//                item.name = area[index];
//            }];
//        }];
//
//        [dataSource addObject:item1];
//    }
    
    
    NSString *path = [[NSBundle mainBundle]pathForResource:@"province" ofType:@"json"];
    NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

    
    NSArray *provinces = [NSObject jsonToObject:content];;
    for (NSDictionary *tmp in provinces) {
        // 创建第一级数据
        LDPickerItem *item1 = [[LDPickerItem alloc]init];
        item1.name = tmp[@"label"];
        item1.obj = tmp[@"value"];
        NSArray *arr = [tmp objectForKey:@"children"];
        if (![arr isKindOfClass:[NSNull class]] && arr.count > 0) {
            // 配置第二级数据
            [item1 loadData:arr.count config:^(LDPickerItem *item, NSInteger index) {
                NSDictionary *cityDic = arr[index];
                item.name = cityDic[@"label"];
                item.obj = cityDic[@"value"];
                NSArray *area = [cityDic objectForKey:@"children"];
                if (![arr isKindOfClass:[NSNull class]] && arr.count > 0) {
                    // 配置第三极数据
                    [item loadData:area.count config:^(LDPickerItem *item, NSInteger index) {
                        NSDictionary *areaDic = area[index];
                        item.name = areaDic[@"label"];
                        item.obj = areaDic[@"value"];
                    }];
                } else {
                    [item loadData:1 config:^(LDPickerItem *item, NSInteger index) {
                        item.name = @"-";
                        item.obj = cityDic[@"value"];
                    }];
                }
            }];
        } else {
            // 配置第二级数据
            [item1 loadData:1 config:^(LDPickerItem *item, NSInteger index) {
                item.name = @"-";
                item.obj = tmp[@"value"];
                // 配置第三极数据
                [item loadData:1 config:^(LDPickerItem *item, NSInteger index) {
                    item.name = @"-";
                    item.obj = tmp[@"value"];
                }];
                
            }];
        }
        
        [dataSource addObject:item1];
    }
    return dataSource;
    
}
@end
@interface LDAddressPickerView()

@property (nonatomic, strong) NSMutableArray *currentItems;
@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, copy) LDPickerViewHandler commitHandler;
@property (nonatomic, copy) LDPickerViewHandler autoHandler;
@property (nonatomic, strong)LDBottomPopView *popView;
@property (nonatomic, assign) int compantsCount;

@end
@implementation LDAddressPickerView

- (instancetype)initWithCompantsCount:(int)compantsCount {
    if (self = [super initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, RatioHeight(121))]) {
        self.compantsCount = compantsCount;
        [self configureUIWithData:LDPickerItem.loadData];
    }
    return self;
}
- (instancetype)initWithDepartmentData:(NSArray *)datas {
    if (self = [super initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, RatioHeight(121))]) {
        [self configureUIWithData:datas];
    }
    return self;
}

- (instancetype)initWithDepartmentData:(NSArray *)datas compantsCount:(int)compantsCount {
    if (self = [super initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, RatioHeight(121))]) {
        self.compantsCount = compantsCount;
        [self configureUIWithData:datas];
    }
    return self;
}

- (void) didSelectedHandler:(LDPickerViewHandler)handler {
    
    self.commitHandler = handler;
}

- (void) autoSelectedHandler:(LDPickerViewHandler)handler {
    self.autoHandler = handler;
}

- (void) loadDates:(NSArray *)datas {
    self.dataSource = [NSArray arrayWithArray:datas];
    [self configDefaultItemFromDatas:datas];
    [self.pickerView reloadAllComponents];
}
#pragma mark - 按钮点击事件
- (void)commitButtonClick:(UIButton *)button {
    // 选择结果回调
    [self commitSelectedData:self.commitHandler];
}

- (void) commitSelectedData:(LDPickerViewHandler)handler {
    
    if (handler) {
        
        NSMutableString *str = [[NSMutableString alloc]init];
        NSMutableArray *tempItems = [NSMutableArray arrayWithArray:self.currentItems];
        for (int i = 0; i< tempItems.count; i++) {
            LDPickerItem *item = tempItems[i];
            if (str.length <= 0) {
                [str appendString:item.name];
                continue;
            }
            
            if (![item.name isEqualToString:@"-"]) {
                [str appendString:@"·"];
                [str appendString:item.name];
            }
            if (i==1 && (item.datas == nil || item.datas.count==0) && self.currentItems.count == 3) {
                [self.currentItems removeLastObject];
                break;
            }
        }
        
        handler(self.currentItems, [str copy]);
    }
}
- (void)layoutSubviews {
    [super layoutSubviews];
}

-(instancetype)init {
    if (self = [super initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, RatioHeight(121))]) {
        [self configureUIWithData:LDPickerItem.loadData];
    }
    return self;
}

- (void)configureUIWithData:(NSArray *)data {
    _pickerView = [[PGPickerView alloc] initWithFrame:CGRectMake(RatioWidth(30), 0, self.width - RatioWidth(30) * 2, self.height)];
    [self addSubview:_pickerView];
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    self.pickerView.type = PGPickerViewLineTypeline;
    
//        [self.pickerView selectRow:5 inComponent:0 animated:true];
//        [self.pickerView selectRow:7 inComponent:1 animated:true];
    self.pickerView.rowHeight = RatioWidth(30);
    self.pickerView.isHiddenMiddleText = false;
    self.pickerView.textFontOfOtherRow = TGAutoFont(14);
    self.pickerView.textFontOfSelectedRow = TGAutoFont(14);

    //设置线条的颜色
    self.pickerView.lineBackgroundColor = RGBA(231,231,231,1);
    //设置选中行的字体颜色
    self.pickerView.textColorOfSelectedRow = TitleBlackColor;
    //设置未选中行的字体颜色
    self.pickerView.textColorOfOtherRow = RGBA(204,204,204,1);
    self.pickerView.lineHeight = PixelOne;
    [self loadDates:data];
}

#pragma UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(PGPickerView *)pickerView {
//    return 3;//self.currentItems.count;
    return self.compantsCount > 0 ? self.compantsCount: 3;
}

- (NSInteger)pickerView:(PGPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return self.dataSource.count;
    } else {
        LDPickerItem *item = [self.currentItems objectAtIndex:component - 1];
        return item.datas.count;
    }
}
#pragma UIPickerViewDelegate
- (nullable NSString *)pickerView:(PGPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {
        LDPickerItem *item = [self.dataSource objectAtIndex:row];
        return item.name;
    } else {
        LDPickerItem *item = [self.currentItems objectAtIndex:component - 1];
        if (item.datas.count > row) {
            
            LDPickerItem *item1 = [item.datas objectAtIndex:row];
            return item1.name;
        }
    }
    return @"---";
}

- (void)pickerView:(PGPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    NSLog(@"row = %ld component = %ld", row, component);
    if (component == 0) {
        LDPickerItem *item = [self.dataSource objectAtIndex:MIN(row, self.dataSource.count-1)];
        [self replaceItem:item atIndex:0];
    } else {
        
        if (self.currentItems.count > component - 1 ) {
            LDPickerItem *item = [self.currentItems objectAtIndex:component - 1];
            
            if (item.datas.count > row) {
                LDPickerItem *item1 = [item.datas objectAtIndex:row];
                [self replaceItem:item1 atIndex:component];
            }
        }
    }
    
    [self reloadPickerAtIndex:component + 1];
    if (self.autoEnable) {
        [self commitSelectedData:self.autoHandler];
    }
}

#pragma mark - 递归分配数据
- (void) configDefaultItemFromDatas:(NSArray *)datas {
    
    if (datas.count > 0) {
        LDPickerItem *item = [datas firstObject];
        [self.currentItems addObject:item];
        if (item.datas) {
            [self configDefaultItemFromDatas:item.datas];
        }
    }
}

- (void) replaceItem:(LDPickerItem *)item atIndex:(NSInteger)index {
    
    if (self.currentItems.count > index) {
        [self.currentItems replaceObjectAtIndex:index withObject:item];
    } else {
        [self.currentItems addObject:item];
    }
    
    if (item.datas.count > 0) {
        LDPickerItem *item1 = [item.datas firstObject];
        index++;
        [self replaceItem:item1 atIndex:index];
    }
}

- (void) reloadPickerAtIndex:(NSInteger)index {
    
    if (index >= self.currentItems.count) {
        return;
    }
    
    [self.pickerView reloadComponent:index];
    [self.pickerView selectRow:0 inComponent:index animated:YES];
    index++;
    [self reloadPickerAtIndex:index];
}

#pragma mark - lazy method
- (NSMutableArray *)currentItems {
    if (_currentItems == nil) {
        _currentItems = [NSMutableArray array];
    }
    return _currentItems;
}
- (void)show{
    if (!_popView) {
        _popView = [[LDBottomPopView alloc] initWithAlertView:self];
        [_popView addTagert:self selector:@selector(sureAction:)];
    }
    [_popView show];
}
- (void)sureAction:(id)sender{
    [self commitButtonClick:nil];
    [_popView hide];
    
}
@end
